Angular Services

In this tutorial, we shall see how to create a service in angular and inject them into the component for using the service.

What is a service in angular?

Angular services are singleton objects, which get instantiated only once during the lifetime of an application.

They are used to perform business logic and make them available to the component.

A component should mainly focus on presenting data and delegate data access to a service.

Services can be used as a medium of communication between components.

What is Dependency Injection?

A service can be used by any component by injecting the service inside the constructor of the component and this is termed as Dependency Injection.

Let's start with an example program. First, create an angular application using

ng new angular-app

Then get into the project using

cd angular-app

Let's create a service using

ng g s services/user

The above command is used to create a service with the name UserService inside the services folder. Below is the boilerplate code generated for the service.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor() { }
}

A class that is decorated with @Injectable() will behave like a service. The @Injectable() gets an object as a parameter. It has a parameter providedIn with root value. This means the service is available to the entire application.

Next, let's modify the UserService class. Let's create two functions setUser() and getUser().

The setUser() function is used to set the name of the user. The getUser() function is used to get the name of the user.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  private userName:string;
  constructor() { }

  setUser(userName:string) {
    this.userName = userName;
  }

  getUser(){
    return this.userName;
  }
}

Now in app.component.ts file lets inject the service inside the constructor and call the setUser() function of UserService with a name inside the constructor.

import { Component } from "@angular/core";
import { UserService } from "./services/user.service";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(private userService: UserService) {
    this.userService.setUser("ReadersBuddy!");
  }
}

Now we have set the variable userName in UserService using setUser() function in the constructor of the AppComponent.

Next, let's create another component where we can get the userName from the UserService. Create a component named HomeComponent using the following angular cli command.

ng g c home

Next, modify the component to get the userName from UserService by injecting the UserService to its constructor and calling the getUser() function to get the userName.

import { Component, OnInit } from "@angular/core";
import { UserService } from "../services/user.service";
@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.css"]
})
export class HomeComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userName = this.userService.getUser();
  }
}

Now in home.component.html add the following

<p>Welcome {{userName}}</p>

The home.component.ts file we get the userName by calling the getUser() function and set it to the userName variable of the HomeComponent.

Now, wherever you use the selector string app-home you can see the output as

Welcome ReadersBuddy!


Most Read